import { ConfigService } from '@nestjs/config';
import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Observable } from 'rxjs';
import { pathToRegexp } from 'path-to-regexp';

interface route {
  method: string;
  path: string;
}

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  private globalWhiteList: route[] = [];
  constructor(private readonly config: ConfigService) {
    super();
    this.globalWhiteList = [].concat(this.config.get('prem.router.whitelist') || []);
  }
  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const isInWhiteList = this.checkWhiteList(context);
    if (isInWhiteList) return true;
    return super.canActivate(context);
  }

  // 检查接口是否在白名单内
  checkWhiteList(context: ExecutionContext): boolean {
    const req: Request = context.switchToHttp().getRequest();
    const method = req.method;
    const url = req.url;
    return this.globalWhiteList.some((route) => route.method.toUpperCase() === method.toUpperCase() && pathToRegexp(route.path).regexp.exec(url));
  }
}
